<?php

/*
	Class: Dealers_AdminController

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>

	About: See Also
		- <Cts_Controller_Action_Admin>
*/
class Dealers_AdminController extends Cts_Controller_Action_Admin {

	/* Group: Instance Methods */

	function init() {
		parent::init();
	}

	/* Group: Actions */

	/*
		Function: index
			Displays a list of all dealers as well as some bulk actions and filters.

		View Variables:
			$countries - An array of countries to populate the country filter dropdown.
			$dealer_types - An array of dealer types to populate the dealer type filter dropdown.
			$dealers - An array of dealers to list.
			$q - The search keywords, if submitted.
	*/
	function indexAction() {
		$request = new Cts_Request($this->getRequest());
		$dealers_table = new DealersViewDealers();
		$where = null;

		if ($request->has('q')) {
			$where = $dealers_table->getWhereClauseByKeywords($request->q);
			$this->view->q = $request->q;
		} else {
			if ($request->has('c') || $request->has('dt')) {
				if ($request->has('c')) {
					$country_code = $request->c;
					$this->view->c = $request->c;
				} else {
					$country_code = null;
				}
				if ($request->has('dt')) {
					$dealer_type = $request->dt;
					$this->view->dt = $request->dt;
				} else {
					$dealer_type = null;
				}
				$where = $dealers_table->getWhereClauseByAdminFilter($country_code, $dealer_type);
			}
		}
		$params = array();
        $per_page = Cts_Registry::get('admin_dealers_per_page');
		$page = $this->_request->getParam('page', 0);
		$total = $dealers_table->getCountByWhereClause($where);
		$url = "/dealers/admin/index";
		$order = "name asc";
		$this->makePager($page, $per_page, $total, $url, $params);
		$tmp_dealers = $dealers_table->fetchAll($where, $order, $per_page, $per_page * $page);
		if (!is_null($tmp_dealers)) {
			$this->view->dealers = $tmp_dealers->toArray();
		}
		$countries_table = new DealersViewCountriesInUse();
		$this->view->countries = $countries_table->getOptionsArray("Show All Countries");
		$dealer_types_table = new DealersDealerTypes();
		$this->view->dealer_types = $dealer_types_table->getOptionsArray("Show All Dealer Types");
	}

	/*
		Function: edit
	*/
	function editAction() {
		$request = new Cts_Request($this->getRequest());
	   	$errors = array();
		$dealer_id = 0;
		if (!$request->has('id')) {
        	$this->_redirect("/default/auth/missing");
		} else {
			$dealers_table = new DealersDealers();
			$dealer_id = $request->id;
			if ($dealer_id == -1) {
				if ($request->has('dealer_type_id')) {
					$dealer = array(
						'id' => "-1",
						'dealer_type_id' => $request->dealer_type_id,
						'name' => "New Dealer",
					);
					$this->view->is_new = true;
				} else {
					$errors[] = "Dealer type ID not supplied.";
				}
			} else {
				$dealer = $dealers_table->get($dealer_id);
			}
			if (count($dealer) >= 1) {
				$this->view->statuses = array(
					'active' => "Active",
					'inactive' => "Inactive",
					'hold' => "On Hold",
					);
				$this->view->states = Cts_Common::getUsStatesArray("Choose a state...");
				$countries_table = new Countries();
				$this->view->countries_single_select = $countries_table->getOptions("Choose a country...");
				$categories_table = new DealersCategories();
				$this->view->countries_multi_select = $countries_table->getOptions();
				$this->view->dealer_categories = $categories_table->getOptions();
				if ($dealer['id'] >= 1) {
					$dealer_countries_table = new DealersViewDealersCountries();
					$associate_countries_array = $dealer_countries_table->getCountryIdsByDealerId($dealer_id);
					$this->view->associated_countries_array = $associate_countries_array;
					$this->view->associated_countries_string = implode(",", $associate_countries_array);
					$dealers_categories_table = new DealersViewDealersCategories();
					$this->view->dealer_categories_selected = $dealers_categories_table->getCatIdsByDealerId($dealer_id);
				}
				$this->view->dealer = $dealer;
				$this->view->dealer_id = $dealer_id;
				if ($this->getRequest()->isPost()) {
					$request->addValidator("dealer_type_id", "Dealer type ID is required.");
					$request->addValidator("status", "Please choose a dealer status.");
					$request->addValidator("dealer_code", "Please enter a dealer ID.");
					$request->addValidator("name", "Please enter a name.");
					if ($request->dealer_type_id == "2") {
						$request->addValidator("website_url", $this->_T("Invalid Website URL."));
					}
					if (!$request->isValid()) {
						$errors = array_merge($errors, $request->getValidationErrors());
					}
					if (count($errors) <= 0) {
						$dealer['dealer_type_id'] = $request->dealer_type_id;
						$dealer['status'] = $request->status;
						$dealer['code'] = $request->dealer_code;
						$dealer['name'] = $request->name;
						$dealer['last_modified_on'] = date(DB_DATETIME_FORMAT);
						switch ($request->dealer_type_id) {
							case "1":
								$dealer['address1'] = $request->address1;
								$dealer['address2'] = $request->address2;
								$dealer['city'] = $request->city;
								$dealer['state'] = $request->state;
								$dealer['zip'] = $request->zip;
								$dealer['country_code'] = $request->country_code;
								$dealer['intl_calling_code'] = $request->intl_calling_code;
								$dealer['phone_number'] = $request->phone_number;
								$dealer['website_url'] = $request->website_url;
								$dealer['short_description'] = $request->short_description;
								$dealer['latitude'] = $request->latitude;
								$dealer['longitude'] = $request->longitude;
								break;
							case "2":
								$dealer['website_url'] = $request->website_url;
								$dealer['logo_filename'] = $request->logo_filename;
								if (is_null($request->online_sync)) {
									$dealer['online_sync'] = '0';
								} else {
									$dealer['online_sync'] = $request->online_sync;
								}
								$dealer['online_sync_url'] = $request->online_sync_url;
								break;
						}
						$this->view->dealer = $dealer;
						$params = array();
						if ($dealer_id >= 1) {
							// UPDATE EXISTING
							$params['dealer'] = $dealer;
							$params = $this->_cts_plugin->doFilter("dealers_admin_edit_pre_update", $params); // FILTER HOOK
							$dealer = $params['dealer'];
							$where = $dealers_table->getAdapter()->quoteInto("id = ?", $dealer['id']);
							if ($dealers_table->update($dealer, $where) >= 1) {
								$this->view->success = "Dealer successfully updated.";
								$this->view->dealer = null;
							} else {
								$errors[] = "Unable to update the dealer due to a database error.";
							}
						} else {
							// INSERT NEW
							$dealer['id'] = null;
							$dealer['created_on'] = date(DB_DATETIME_FORMAT);
							$params['dealer'] = $dealer;
							$params = $this->_cts_plugin->doFilter("dealers_admin_edit_pre_insert", $params); // FILTER HOOK
							$dealer = $params['dealer'];
							$dealer_id = $dealers_table->insert($dealer);
							if ($dealer_id >= 1) {
								$this->view->success = "Dealer successfully added.";
								$this->view->dealer = null;
								$this->view->dealer_id = $dealer_id;
							} else {
								$errors[] = "Unable to add the dealer due to a database error.";
							}
						}
						if (count($errors) === 0) {
							if ($request->has('dealer_categories') && count($request->dealer_categories) >= 1) {
								$dealer_categories_table = new DealersDealersCategories();
								$dealer_categories_table->deleteByDealerId($dealer_id);
								$dealer_categories_table->insertMulti($dealer_id, $request->dealer_categories);
							}
							if ($request->has('associated_countries') && count($request->associated_countries) >= 1) {
								$dealer_countries_table = new DealersDealersCountries();
								$dealer_countries_table->deleteByDealerId($dealer_id);
								$dealer_countries_table->insertMulti($dealer_id, $request->associated_countries);
							}
						}
					}
				}
			} else {
				$errors[] = "Dealer not found.";
			}
		}
		$this->view->errors = $errors;
	}

	/*
		Function: delete
	*/
	function deleteAction() {
		$request = new Cts_Request($this->getRequest());
	   	$errors = array();
		$dealer_id = 0;
		if ($request->has('id')) {
			$dealer_id = $request->id;
			$dealers_table = new DealersDealers();
			if ($this->getRequest()->isPost()) {
				if ($dealers_table->deleteDealer($dealer_id)) {
					$this->view->success = "Dealer deleted.";
				} else {
					$errors[] = "Unable to delete the dealer due to a database error.";
				}
			} else {
				$dealer = $dealers_table->get($dealer_id);
				if (count($dealer) >= 1) {
					$this->view->dealer = $dealer;
				} else {
					$errors[] = "Dealer not found.";
				}
			}
		} else {
			$errors[] = "Dealer ID was not supplied.";
		}
		$this->view->errors = $errors;
	}

	/*
		Function: bulkdelete
	*/
	function bulkdeleteAction() {
		$request = new Cts_Request($this->getRequest());
		$errors = array();
		if ($request->has('bulk_checkbox')) {
			$dealer_ids = $request->bulk_checkbox;
			$dealers_table = new DealersDealers();
			if ($this->getRequest()->isPost()) {
				if ($dealers_table->deleteBulk($dealer_ids)) {
					$this->view->success = "Dealers deleted.";
				} else {
					$errors[] = "Unable to delete the dealers due to a database error.";
				}
			} else {
				$dealers = $dealers_table->getBulk($dealer_ids);
				if (count($dealers) >= 1) {
					$this->view->dealers = $dealers;
				} else {
					$errors[] = "No dealers found.";
				}
			}
		} else {
			$errors[] = "No dealers were selected.";
		}
	}

}
